<?php

if( ! function_exists('pr') ){
	function pr($val){
		echo '<pre>';
		print_r($val);
		echo '</pre>';
	}
}



if( ! function_exists('alert') ){
	/**
	 * 输出JS弹窗alert
	 * @param  string $msg  消息
	 * @param  string $url  跳转的方式
	 *                      #:无任何操作
	 *                      back:返回上一页,
	 *                      reload:重新打开
	 *                      close:关闭
	 *                      普通url:跳转到该URL
	 */
	function alert($msg='',$url='back'){
		echo '<script>';
		if( $msg ){
			echo 'alert("'.$msg.'");';
		}

		switch ( strtolower($url) ) {
			case '#':
				break;
			case 'back':
				echo 'window.history.go(-1);window.location.reload();';
				break;
			case 'close':
				echo 'window.opener=null;window.close();';
				break;
			case 'reload':
				echo 'window.location.reload();';
				break;
			default:
				echo 'window.location.href="'.$url.'";';
				break;
		}


		echo '</script>';
	}
}

/**
 * 检查手机号码格式
 * @param unknown_type $num
 * @return number
 */
function is_phone($num){
	return preg_match('/^[1][3456789][0-9]{9}$/',$num);
}


if ( ! function_exists('check_input') ) {
	/**
	 * 检查输入的参数
	 * @param  array  $data                	要检查的数组.默认$_REQUEST
	 * @param  array  $must_provide_fields 	输入数组中必须有的字段,如array('islife','channelid')
	 * @param  array  $default 				设置默认值,如果输入数组中没有该字段,则设其为默认值,如array('page'=>10);
	 * @return mixed                       	检查不通过返回FALSE
	 */
	function check_input($data=array(),$must_provide_fields=array(),$default=array()){

		if( empty($data) ){
			$data = &$_REQUEST;
		}
		//检查必须提供的字段是否存在,一个不存在即返回FALSE
		if( !empty($must_provide_fields) ){
			foreach ($must_provide_fields as $field) {
				if( !array_key_exists($field, $data) ){
					return FALSE;
				}
			}
		}

		$rtn=array();
		//清理各个输入字段
		foreach ($data as $field => $val) {
			switch ($field) {
				case 'phone' ://如果手机号码格式不正确即设为0;
					$val = trim($val);
					$rtn[$field] = preg_match('/^[1][3456789][0-9]{9}$/',$val) ? $val : 0;
					break;
				case 'tid':
					$val = trim($val);
					if ( !is_numeric($val) || ($val<=0) ){
							$temp = 0;
					}
					$rtn[$field] = isset($temp)?0:$val;
					break;
				//=====其他
				default:
					$rtn[$field]= htmlspecialchars( $val , ENT_QUOTES );
					break;
			}
		}
		//设置默认值
		foreach ($default as $field => $default_value) {
			$rtn[$field] = isset($data[$field]) ? $data[$field] :  $default_value ;
		}
		//返回处理结果
		return $rtn;
	}
}

function debug($msg='',$data=''){
	MyDebug::log($msg,$data);
// 	if ( defined('IS_TEST') && IS_TEST ) {
// 		if( empty($msg) && empty($data) ){
// 			$log = debug_backtrace();
// 			$str  = '';
// 			$prev = $log[1];
// 			if ( isset($prev['class']) ) {
// 				$str.= $prev['class'];
// 			}
// 			if ( isset($prev['type']) ) {
// 				$str.= $prev['type'];
// 			}
// 			if ( isset($prev['function']) ) {
// 				$str.= $prev['function'];
// 			}
// 			$str.='(';
// 			if( $prev['args'] ){
// 				$str.=implode(',', $prev['args']);
// 			}
// 			$str.=')';
// 			$file = strtr( $log[0]['file'],array(APPPATH=>'','\\'=>'/'));
// 			$str.=' --'.$file;
// 			$line = $log[0]['line'];
// 			$str .= '['.$line.']';
// 			MyDebug::push('_backtrace', $str);
// 		}else{
// 			MyDebug::log($msg,$data);
// 		}
		
		
// 	}
}


	/**
	 * 生成随机唯一邀请码
	 */
function get_invitation_code($count=6){
		$code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $rand = $code[rand(0,25)]
            .strtoupper(dechex(date('m')))
            .date('d').substr(time(),-5)
            .substr(microtime(),2,5)
            .sprintf('%02d',rand(0,99));
        for(
            $a = md5( $rand, true ),
            $s = '0123456789ABCDEFGHIJKLMNOPQRSTUV',
            $d = '',
            $f = 0;
            $f < $count;
            $g = ord( $a[ $f ] ),
            $d .= $s[ ( $g ^ ord( $a[ $f + 8 ] ) ) - $g & 0x1F ],
            $f++
        );
        return  $d;

}
/**
 * 获取手机系统
 * 返回:ios,android,other
 */
function get_mobile_system(){
	static $system;
	if( empty($system) ){
		$ua = strtolower($_SERVER['HTTP_USER_AGENT']);
		if( strpos($ua,'iphone') || strpos($ua,'ipad') ){
			$system = 'ios';
		}else if(strpos($ua,'android')){
			$system = 'android';
		}else{
			$system = 'other';
		}

		if( !empty($_REQUEST['system']) ){
			$system = $_REQUEST['system'];
		}
	}
	return $system;
}


/**
 * PHP获取字符串中英文混合长度
 * @param $str string 字符串
 * @return 返回长度，1中文=1位，2英文=1位
 */
function strLength($str){
	$str = mb_convert_encoding($str,'UTF-8','ASCII,UTF-8,GBK');
	$len = 0;
	$i=0;
	while( $char = mb_substr($str,$i++,1,'UTF-8') ){
		if(ord($char)<127){
			$len++;
		}else{
			$len+=2;
		}
	}
	return ceil($len/2);
}

/**
 * 判断是否手机请求
 */
function is_mobile(){
	if (PHP_SAPI === 'cli') {
		return false;
	}
	static $MY_is_mobile = FALSE;
	if ($MY_is_mobile !== FALSE) {
		return $MY_is_mobile;
	}
	
	$_SERVER ['ALL_HTTP'] = isset ( $_SERVER ['ALL_HTTP'] ) ? $_SERVER ['ALL_HTTP'] : '';
	$mobile_browser = '0';
	if (preg_match ( '/(up.browser|up.link|mmp|symbian|smartphone|midp|wap|phone|iphone|ipad|ipod|android|xoom)/i', strtolower ( $_SERVER ['HTTP_USER_AGENT'] ) ))
		$mobile_browser ++;
	
	if ((isset ( $_SERVER ['HTTP_ACCEPT'] )) and (strpos ( strtolower ( $_SERVER ['HTTP_ACCEPT'] ), 'application/vnd.wap.xhtml+xml' ) !== false))
		$mobile_browser ++;
	
	if (isset ( $_SERVER ['HTTP_X_WAP_PROFILE'] ))
		$mobile_browser ++;
	
	if (isset ( $_SERVER ['HTTP_PROFILE'] ))
		$mobile_browser ++;
	
	$mobile_ua = strtolower ( substr ( $_SERVER ['HTTP_USER_AGENT'], 0, 4 ) );
	$mobile_agents = array ('w3c ', 'acs-', 'alav', 'alca', 'amoi', 'audi', 'avan', 'benq', 'bird', 'blac', 'blaz', 'brew', 'cell', 'cldc', 'cmd-', 'dang', 'doco', 'eric', 'hipt', 'inno', 'ipaq', 'java', 'jigs', 'kddi', 'keji', 'leno', 'lg-c', 'lg-d', 'lg-g', 'lge-', 'maui', 'maxo', 'midp', 'mits', 'mmef', 'mobi', 'mot-', 'moto', 'mwbp', 'nec-', 'newt', 'noki', 'oper', 'palm', 'pana', 'pant', 'phil', 'play', 'port', 'prox', 'qwap', 'sage', 'sams', 'sany', 'sch-', 'sec-', 'send', 'seri', 'sgh-', 'shar', 'sie-', 'siem', 'smal', 'smar', 'sony', 'sph-', 'symb', 't-mo', 'teli', 'tim-', 'tosh', 'tsm-', 'upg1', 'upsi', 'vk-v', 'voda', 'wap-', 'wapa', 'wapi', 'wapp', 'wapr', 'webc', 'winw', 'winw', 'xda', 'xda-'); 
	if (in_array ( $mobile_ua, $mobile_agents ))
		$mobile_browser ++;
	
	if (strpos ( strtolower ( $_SERVER ['ALL_HTTP'] ), 'operamini' ) !== false)
		$mobile_browser ++;
		
		// Pre-final check to reset everything if the user is on Windows
	if (strpos ( strtolower ( $_SERVER ['HTTP_USER_AGENT'] ), 'windows' ) !== false)
		$mobile_browser = 0;
		
		// But WP7 is also Windows, with a slightly different characteristic
	if (strpos ( strtolower ( $_SERVER ['HTTP_USER_AGENT'] ), 'windows phone' ) !== false)
		$mobile_browser ++;
	
	$MY_is_mobile = $mobile_browser;
	if ($mobile_browser > 0)
		return true;
	else
		return false;
}
/**
 * 利用curl请求数据
 * @param string	 $url		要请求的URL
 * @param array		 $data		要发送的数据
 * @param string	 $method	'get'(默认)/'post'
 * @param int		 $timeout	超时,默认30秒
 * @return mixed
 */
function requestData($url,$data=array(),$method='get',$timeout=30){
	$ch = curl_init();
	if( 'get' == $method ){
		if( !empty($data) ){
			$url.='?';
			foreach ($data as $k => $v) {
				$url.=$k.'='.$v.'&';
			}
			$url = rtrim($url,'&');
		}
	}
	curl_setopt($ch,CURLOPT_URL,$url);
	curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);//TRUE 将curl_exec()获取的信息以字符串返回，而不是直接输出
	curl_setopt($ch,CURLOPT_HEADER,0);//TRUE会将头文件的信息作为数据流输出。
	curl_setopt($ch,CURLOPT_TIMEOUT,$timeout);//30秒超时
	if('post' == $method){
		curl_setopt($ch,CURLOPT_POST,1);
		curl_setopt($ch,CURLOPT_POSTFIELDS,$data);
	}

	$rtn = curl_exec($ch);
	curl_close($ch);
	return $rtn;
}

/**
 * 产生一个随机数数组
 * @param	 int		 $count		随机数个数
 * @param	 int		 $min
 * @param	 int		 $max
 * @return	 array
 */
function randBatch($count,$min,$max){
	$rtn = array();
	while( count($rtn)<$count ){
		$rtn[ mt_rand($min,$max) ] = null;
	}
	
	return array_keys($rtn);
}
/**
 * 安全代码处理
 *
 * @param string $string
 *        	要处理的文本
 * @param string $operation
 *        	处理方式(DECODE:解码,ENCODE:编码)
 * @param string $key
 *        	密匙
 * @param int $expiry
 *        	过期时间
 * @return string
 */
function authcode($string, $operation = 'DECODE', $key = '', $expiry = 0) {
	$ckey_length = 4;
	$key  = md5 ( $key != '' ? $key : config_item ( 'encryption_key' ) );
	$keya = md5 ( substr ( $key, 0, 16 ) );
	$keyb = md5 ( substr ( $key, 16, 16 ) );
	$keyc = $ckey_length ? ($operation == 'DECODE' ? substr ( $string, 0, $ckey_length ) : substr ( md5 ( microtime () ), - $ckey_length )) : '';
	
	$cryptkey = $keya . md5 ( $keya . $keyc );
	$key_length = strlen ( $cryptkey );
	
	$string = $operation == 'DECODE' ? base64_decode ( substr ( $string, $ckey_length ) ) : sprintf ( '%010d', $expiry ? $expiry + time () : 0 ) . substr ( md5 ( $string . $keyb ), 0, 16 ) . $string;
	$string_length = strlen ( $string );
	
	$result = '';
	$box = range ( 0, 255 );
	
	$rndkey = array ();
	for($i = 0; $i <= 255; $i ++) {
		$rndkey [$i] = ord ( $cryptkey [$i % $key_length] );
	}
	for($j = $i = 0; $i < 256; $i ++) {
		$j = ($j + $box [$i] + $rndkey [$i]) % 256;
		$tmp = $box [$i];
		$box [$i] = $box [$j];
		$box [$j] = $tmp;
	}
	
	for($a = $j = $i = 0; $i < $string_length; $i ++) {
		$a = ($a + 1) % 256;
		$j = ($j + $box [$a]) % 256;
		$tmp = $box [$a];
		$box [$a] = $box [$j];
		$box [$j] = $tmp;
		$result .= chr ( ord ( $string [$i] ) ^ ($box [($box [$a] + $box [$j]) % 256]) );
	}
	
	if ($operation == 'DECODE') {
		if ((substr ( $result, 0, 10 ) == 0 || substr ( $result, 0, 10 ) - time () > 0) && substr ( $result, 10, 16 ) == substr ( md5 ( substr ( $result, 26 ) . $keyb ), 0, 16 )) {
			return substr ( $result, 26 );
		} else {
			return '';
		}
	} else {
		return $keyc . str_replace ( '=', '', base64_encode ( $result ) );
	}
}
/**
 * 下载远程用户头像
 * @param string $url
 * @return boolean|string
 */
function loadUserHeadImg($url){
	// 检测该URL是否有效
	$head = get_headers($url,TRUE);
	if( !preg_match('/200/',$head[0]) ){
		return FALSE;
	}
	// 检测该资源是否为图片
	if (!preg_match('/image\/(.*)/',$head['Content-Type'],$match)) {
		return FALSE;
	}
	// 计算文件名
	$ext = '.'.$match[1];//图片后缀
	$dir = 'upload/userHeadImg/';//图片保存的目录
	$time = time();
	$i = 0;
	$file = $dir.$time.$i.$ext;//图片文件名
	$localFile = FCPATH.$file;//图片本地路径
	while (file_exists($localFile)) {
		$file = $dir.$time.($i++).$ext;
		$localFile = FCPATH.$file;
	}
	// 下载图片
	ob_start();
    readfile($url);
    $img=ob_get_contents();
    ob_end_clean();
	// 保存图片
    $fh = fopen($localFile,'ab+');
    fwrite($fh, $img);
    fclose($fh);
    unset($img);
    return $file;
}



function array2XmlString($arr,$node='xml'){
	$xml = "<$node>";
	foreach( $arr as $k=>$v ){
		$k = is_numeric($k) ? 'item' : $k;
		if( is_array($v) OR is_object($v) ){
			$xml.= array2XmlString($v,$k);
		}else{
			$xml.= "<$k><![CDATA[$v]]></$k>";
		}
	}
	$xml .= "</$node>";
	return $xml;
}

/**
 * 分页验证
 */
if (! function_exists ( 'check_page' )) {
	function check_page($pageSize = 10) {
		$page = empty ( $_REQUEST ['page'] ) ? 1 : $_REQUEST ['page'];
		$page = is_numeric ( $page ) ? $page : 1;
		$page = ($page > 0) ? $page : 1;
		$res ['page'] = $page;
		$res ['size'] = $pageSize;
		return $res;
	}
}

/**
 * 生成分页配置项
 *
 * @param int $count
 *        	记录总数
 * @param array $page
 *        	$page['page'];当前页 | $page['size'];每页显示多少条
 * @param int $pageSize
 *        	中间显示多少条
 * @return array
 */
if (! function_exists ( 'pagestring' )) {
	function pagestring($count, $page, $pageSize = 6) {
		if (empty ( $count ) || empty ( $page )) {
			return false;
		}
		$pagecount = ceil ( ( int ) ($count / $page ['size']) );
		$pagestring ['total'] = $count; // 记录总数
		$pagestring ['pagetotal'] = $pagecount; // 总页数
		$pagestring ['page'] = $page ['page']; // 当前页
		$pagestring ['size'] = $page ['size']; // 每页显示多少条
		$pagestring ['pagesize'] = $pageSize; // 中间显示多少条

		return $pagestring;
	}
}

/**
 * 错误提示函数
 *
 * @param string $msg
 *        	[提示信息]
 *
 */
if (! function_exists ( 'error' )) {
	function error($msg, $url = '') {
		header ( 'Content-Type:text/html;charset=utf-8' );
		$msg = @mysql_escape_string ( $msg );
		$msg = strip_tags ( $msg );
		if (empty ( $url )) {
			echo "<script type='text/javascript'>alert('$msg');window.history.back();</script>";
		} elseif ($url == 'exit') {
			echo "<script type='text/javascript'>alert('$msg');window.close();</script>";
		} else {
			$url = site_url ( $url );
			echo "<script type='text/javascript'>alert('$msg');location.href='$url';</script>";
		}
		die ();
	}
}

/**
 * 成功提示函数
 *
 * @param string $url
 *        	跳转地址
 * @param string $msg
 *        	提示信息
 */
if (! function_exists ( 'success' )) {
	function success($url, $msg) {
		header ( 'Content-Type:text/html;charset=utf-8' );
		if (! empty ( $url ) && $url != 'refresh') {
			$url = site_url ( $url );
			echo "<script type='text/javascript'>alert('$msg');location.href='$url'</script>";
		} elseif ($url == 'refresh') {
			echo "<script type='text/javascript'>alert('$msg');location.replace(document.referrer);</script>";
		} else {
			echo "<script type='text/javascript'>alert('$msg');window.close();</script>";
		}
		die ();
	}
}








